package fileupdownYouhua.web;

import fileupdownYouhua.dao.DatabaseDaoIml;
import fileupdownYouhua.service.UploadMeth;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import java.io.IOException;
import java.io.InputStream;

import java.util.UUID;

@WebServlet("/upload")
@MultipartConfig
public class FileUpload extends HttpServlet {
    public static final String URL = "http://localhost:8080/resourse";

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取文件部分
        Part part = req.getPart("file");
        //获取上传的文件名
        String submittedFileName = part.getSubmittedFileName();
        // 生成唯一的文件ID
        String fileId = UUID.randomUUID().toString();
        // 获取文件内容流
        InputStream fileContent = part.getInputStream();
        String url = URL+submittedFileName;

        //文件保存的操作
        UploadMeth.UploadMethService(submittedFileName,fileContent);

        //数据库的操作
        new DatabaseDaoIml().addBase(submittedFileName,fileId,url);

        resp.sendRedirect("/index");
    }

}
